<template>
  <div class="login">
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="user.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'
export default {
  data() {
    return {
      user: {
        username: "",
        password: ""
      }
    };
  },
  methods: {
    async onSubmit() {
      const resp = await axios.post('/api/login', this.user)
      const { code, token } = resp.data
      if(code === 200) {
        ElMessage.success('登录成功，2s点之后之后跳转首页...')
        localStorage.setItem('token', token)
        this.$store.commit('SET_USER', { isLogin: true, username: this.user.username })
        setTimeout(() => {
          this.$router.push('/')
        }, 2000)
      } else {
        ElMessage.error('账户密码错误，请重新输入！！！')
      }
    }
  }
};
</script>

<style scoped>
.login {
  width: 600px;
  margin: auto;
}
</style>
